import { Component, inject, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STPage, STComponent, STColumn, STChange, STModule } from '@delon/abc/st';
import { DelonACLModule } from '@delon/acl';
import { DelonFormModule, SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzFormatEmitEvent, NzTreeModule } from 'ng-zorro-antd/tree';
import { Api } from 'src/app/shared/api/api';
import { DELETED_STATUS_BADGE, RESOURCE_METHOD_ENUM, RESOURCE_METHOD_TAG } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';
import { PublicService } from 'src/app/shared/service/public.service';

import { ResourceEditComponent } from './resource-edit.component';
import { ResourceGroupComponent } from './resource-group.component';

@Component({
  selector: 'app-system-resource-list',
  templateUrl: './resource.component.html',
  imports: [
    PageHeaderModule,
    NzCardModule,
    NzButtonModule,
    STModule,
    DelonACLModule,
    DelonFormModule,
    NzTreeModule,
    NzRadioModule,
    FormsModule,
    NzGridModule,
    NzIconModule
  ]
})
export class ResourceComponent implements OnInit {
  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);

  protected readonly modalService = inject(NzModalService);
  private readonly modal = inject(ModalHelper);
  protected readonly publicService = inject(PublicService);

  params: NzSafeAny = {};
  page: NzSafeAny = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  searchSchema: SFSchema = {};
  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '序号', type: 'no', width: 60 },
    { title: '方法', index: 'method', type: 'tag', tag: RESOURCE_METHOD_TAG, width: 100 },
    { title: '资源', index: 'resource' },
    { title: '备注', index: 'remark' },
    { title: '状态', index: 'deleted', type: 'badge', badge: DELETED_STATUS_BADGE, width: 100 },
    {
      title: '操作',
      width: 150,
      buttons: [
        {
          text: '编辑',
          icon: 'edit',
          click: record => {
            this.editResource(record);
          },
          acl: { ability: ['edit'] }
        },
        {
          text: '删除',
          icon: 'delete',
          click: (record: NzSafeAny) => {
            this.deleteResource(record);
          },
          acl: { ability: ['delete'] }
        }
      ]
    }
  ];
  selectedGroups: NzSafeAny[] = [];
  currentGroup: NzSafeAny = {};
  groupInfo: NzSafeAny[] = [
    {
      title: '全部组',
      key: '0',
      expanded: true,
      children: [],
      group: {}
    }
  ];
  currentResourceFilter = 'false';

  ngOnInit() {
    this.initSearchSchema();
    this.query(null);
    this.queryGroup();
  }

  initSearchSchema() {
    let methods: NzSafeAny = [{ label: '全部', value: '' }].concat(RESOURCE_METHOD_ENUM);
    this.searchSchema = {
      properties: {
        resurce: {
          type: 'string',
          title: '资源'
        },
        remark: {
          type: 'string',
          title: '备注'
        },
        method: {
          type: 'string',
          title: '方法',
          default: false,
          enum: methods,
          ui: {
            widget: 'select',
            acl: { ability: ['query'] }
          }
        }
      }
    };
  }

  queryGroup() {
    let tempTree = [
      {
        title: '全部组',
        key: '0',
        expanded: true,
        children: [],
        group: {}
      }
    ];
    this.http.get(`${Api.BaseResourceApi}/group/tree`).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res && res.code === ResponseCode.SUCCESS) {
          if (!res.data || res.data.length < 1) {
            this.groupInfo = tempTree;
            return;
          }
          tempTree[0].children = res.data;
          this.selectedGroups = [];
          if (this.currentGroup && this.currentGroup.id) {
            this.selectedGroups = [this.currentGroup.id];
          }
          this.groupInfo = tempTree;
        } else {
          this.groupInfo = tempTree;
        }
      }
    });
  }

  groupClick(event: NzFormatEmitEvent): void {
    console.log(event);
    this.currentGroup = event.node?.origin['group'];
    const temp: NzSafeAny = [event.node?.origin.key];
    this.selectedGroups = temp;
    this.query(null);
  }

  addGroup() {
    this.modal.createStatic(ResourceGroupComponent, { parentId: this.currentGroup.id }, { drag: true }).subscribe(() => this.queryGroup());
  }

  editGroup() {
    this.modal.createStatic(ResourceGroupComponent, { record: this.currentGroup }, { drag: true }).subscribe(() => this.queryGroup());
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.query(null);
    }
  }

  query(event: NzSafeAny) {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    let params: NzSafeAny = {};
    if (event) {
      if (event.resurce) params.resurce = event.resurce;
      if (event.remark) params.remark = event.remark;
      if (event.method) params.method = event.method;
      if (event.deleted !== '') params.deleted = event.deleted;
    }
    if (this.currentGroup && this.currentGroup.id) {
      params.groupId = this.currentGroup.id;
    }
    if (this.currentResourceFilter) {
      params.deleted = this.currentResourceFilter === 'true';
    }
    this.http.get(`${Api.BaseResourceApi}/page/${current}/${size}`, params).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res.data;
      }
    });
  }

  add() {
    this.modal
      .createStatic(ResourceEditComponent, { record: { groupId: this.currentGroup.id || '0' } }, { drag: true })
      .subscribe(() => this.st.reload());
  }

  editResource(resource: NzSafeAny) {
    this.modal.createStatic(ResourceEditComponent, resource, { size: 'md', drag: true }).subscribe(() => this.query(null));
  }

  deleteResource(resource: NzSafeAny) {
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">如果您确定要删除请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.delete(`${Api.BaseResourceApi}/${resource.id}`).subscribe((res: NzSafeAny) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.query(null);
              this.msg.success('删除成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('删除失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  enable(record: NzSafeAny) {
    console.log(record);
    this.modalService.confirm({
      nzTitle: '确定禁用吗?',
      nzContent: '<b style="color: red;">如果您确定要启用请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.put(`${Api.BaseResourceApi}/enable/${record.id}`).subscribe((res: NzSafeAny) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.st.reload();
              this.msg.success('启用成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('启用失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  delete(record: NzSafeAny) {
    console.log(record);
    this.modalService.confirm({
      nzTitle: '确定禁用吗?',
      nzContent: '<b style="color: red;">如果您确定要禁用请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.delete(`${Api.BaseResourceApi}/${record.id}`).subscribe((res: NzSafeAny) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.st.reload();
              this.msg.success('禁用成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('禁用失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
